package data

import (
	"061/Sgame/db"
	"061/Sgame/net"
	"061/Sgame/server/game/model"
	"log"
	"time"
)

type Role struct {
	RId        int       `gorm:"column:rid;primaryKey;comment:roleId"`
	UId        int       `gorm:"column:uid;comment:用户UID"`
	NickName   string    `gorm:"column:nick_name;type:varchar(100);comment:nick_name" validate:"min=4,max=20,regexp=^[a-zA-Z0-9_]*$"`
	Balance    int       `gorm:"column:balance;comment:余额"`
	HeadId     int16     `gorm:"column:headId;comment:头像Id"`
	Sex        int8      `gorm:"column:sex;comment:性别，0:女 1男"`
	Profile    string    `gorm:"column:profile;comment:个人简介"`
	LoginTime  time.Time `gorm:"column:login_time;comment:登录时间"`
	LogoutTime time.Time `gorm:"column:logout_time;comment:登出时间"`
	CreatedAt  time.Time `gorm:"column:created_at"`
}

func (r *Role) TableName() string {
	return "role"
}

var RoleResDao = &roleResDao{
	rrChan: make(chan *RoleRes, 100),
}

type roleResDao struct {
	rrChan chan *RoleRes
}

func (r *roleResDao) running() {
	for {
		select {
		case rr := <-r.rrChan:
			err := db.GormDB.
				Model(new(RoleRes)).
				Where("id=?", rr.Id).
				Select("wood", "iron", "stone", "grain", "gold").
				Updates(rr).Error
			if err != nil {
				log.Println("RoleResDao update error", err)
			}
		}
	}
}

func init() {
	go RoleResDao.running()
}

//protobuf
func (r *Role) ToModel() interface{} {
	m := model.Role{}
	m.UId = r.UId
	m.RId = r.RId
	m.Sex = r.Sex
	m.NickName = r.NickName
	m.HeadId = r.HeadId
	m.Balance = r.Balance
	m.Profile = r.Profile
	return m
}
func (r *RoleRes) SyncExecute() {
	RoleResDao.rrChan <- r
	r.Push()
}

/* 推送同步 begin */
func (r *RoleRes) IsCellView() bool {
	return false
}

func (r *RoleRes) IsCanView(rid, x, y int) bool {
	return false
}

func (r *RoleRes) BelongToRId() []int {
	return []int{r.RId}
}

func (r *RoleRes) PushMsgName() string {
	return "roleRes.push"
}

func (r *RoleRes) Position() (int, int) {
	return -1, -1
}

func (r *RoleRes) TPosition() (int, int) {
	return -1, -1
}

func (r *RoleRes) Push() {
	net.Mgr.Push(r)
}
